<template>
  <Dialog v-model="dialogVisible" title="考生签退" width="600px">
    <el-form
      ref="formRef"
      :model="checkOutForm"
      :rules="checkOutRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 考生查找 -->
      <el-divider content-position="left">考生信息</el-divider>
      <el-form-item label="考生查找" prop="candidateSearch">
        <el-input
          v-model="checkOutForm.candidateSearch"
          placeholder="请输入考生姓名、身份证号或准考证号"
          @input="searchCandidate"
          clearable
        >
          <template #append>
            <el-button @click="searchCandidate">搜索</el-button>
          </template>
        </el-input>
      </el-form-item>
      
      <!-- 搜索结果 -->
      <div v-if="candidateList.length > 0" style="margin-bottom: 20px;">
        <el-table :data="candidateList" @row-click="selectCandidate" style="cursor: pointer;">
          <el-table-column prop="candidateName" label="姓名" width="120" />
          <el-table-column prop="examNo" label="准考证号" width="150" />
          <el-table-column prop="checkInTime" label="签到时间" width="150" />
          <el-table-column prop="examStatus" label="考试状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getExamStatusColor(row.examStatus)">
                {{ getExamStatusName(row.examStatus) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 已选考生信息 -->
      <div v-if="selectedCandidate">
        <el-descriptions :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="考生姓名">
            {{ selectedCandidate.candidateName }}
          </el-descriptions-item>
          <el-descriptions-item label="准考证号">
            {{ selectedCandidate.examNo }}
          </el-descriptions-item>
          <el-descriptions-item label="评价职业">
            {{ selectedCandidate.professionName }}
          </el-descriptions-item>
          <el-descriptions-item label="考试场次">
            {{ selectedCandidate.examSession }}
          </el-descriptions-item>
          <el-descriptions-item label="签到时间">
            {{ selectedCandidate.checkInTime }}
          </el-descriptions-item>
          <el-descriptions-item label="考试状态">
            <el-tag :type="getExamStatusColor(selectedCandidate.examStatus)">
              {{ getExamStatusName(selectedCandidate.examStatus) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <!-- 签退信息 -->
      <el-divider content-position="left">签退信息</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="签退时间" prop="checkOutTime">
            <el-date-picker
              v-model="checkOutForm.checkOutTime"
              type="datetime"
              placeholder="选择签退时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签退类型" prop="checkOutType">
            <el-radio-group v-model="checkOutForm.checkOutType">
              <el-radio value="normal">正常签退</el-radio>
              <el-radio value="early">提前离场</el-radio>
              <el-radio value="emergency">紧急退场</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="考试完成情况" prop="examCompletion">
            <el-select v-model="checkOutForm.examCompletion" placeholder="请选择完成情况">
              <el-option label="正常完成" value="completed" />
              <el-option label="提前交卷" value="early_submit" />
              <el-option label="中途退出" value="midway_exit" />
              <el-option label="缺考" value="absent" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考试时长" prop="examDuration">
            <el-input v-model="examDurationDisplay" readonly>
              <template #append>分钟</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 试卷/材料检查 -->
      <el-divider content-position="left">试卷/材料检查</el-divider>
      <el-form-item label="试卷提交状态" prop="paperSubmission">
        <el-checkbox-group v-model="checkOutForm.paperSubmission">
          <el-checkbox label="theory_paper">理论试卷已提交</el-checkbox>
          <el-checkbox label="practice_record">实操记录已提交</el-checkbox>
          <el-checkbox label="answer_sheet">答题卡已提交</el-checkbox>
          <el-checkbox label="draft_paper">草稿纸已回收</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="物品归还" prop="itemsReturn">
        <el-checkbox-group v-model="checkOutForm.itemsReturn">
          <el-checkbox label="exam_tools">考试工具已归还</el-checkbox>
          <el-checkbox label="safety_equipment">安全防护用品已归还</el-checkbox>
          <el-checkbox label="borrowed_items">借用物品已归还</el-checkbox>
          <el-checkbox label="personal_items">个人物品已取回</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <!-- 异常情况 -->
      <el-divider content-position="left">异常情况</el-divider>
      <el-form-item label="考试期间异常" prop="examAnomalies">
        <el-checkbox-group v-model="checkOutForm.examAnomalies">
          <el-checkbox label="equipment_failure">设备故障</el-checkbox>
          <el-checkbox label="health_issue">身体不适</el-checkbox>
          <el-checkbox label="cheating">作弊行为</el-checkbox>
          <el-checkbox label="disruption">扰乱秩序</el-checkbox>
          <el-checkbox label="other">其他异常</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item 
        label="异常详情" 
        prop="anomalyDescription" 
        v-if="checkOutForm.examAnomalies.length > 0"
      >
        <el-input
          v-model="checkOutForm.anomalyDescription"
          type="textarea"
          :rows="3"
          placeholder="请详细描述异常情况及处理过程"
        />
      </el-form-item>
      
      <!-- 成绩相关 -->
      <el-divider content-position="left">成绩信息</el-divider>
      <el-form-item label="是否当场出成绩" prop="immediateScore">
        <el-switch v-model="checkOutForm.immediateScore" />
      </el-form-item>
      
      <div v-if="checkOutForm.immediateScore">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="理论成绩" prop="theoryScore">
              <el-input-number
                v-model="checkOutForm.theoryScore"
                :min="0"
                :max="100"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实操成绩" prop="practiceScore">
              <el-input-number
                v-model="checkOutForm.practiceScore"
                :min="0"
                :max="100"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="综合评价" prop="overallEvaluation">
          <el-rate
            v-model="checkOutForm.overallEvaluation"
            :max="5"
            show-text
            :texts="['很差', '较差', '一般', '良好', '优秀']"
          />
        </el-form-item>
      </div>
      
      <!-- 其他信息 -->
      <el-form-item label="考官评语" prop="evaluatorComments">
        <el-input
          v-model="checkOutForm.evaluatorComments"
          type="textarea"
          :rows="3"
          placeholder="考官对考生表现的评语"
        />
      </el-form-item>
      
      <el-form-item label="签退备注" prop="checkOutRemark">
        <el-input
          v-model="checkOutForm.checkOutRemark"
          type="textarea"
          :rows="2"
          placeholder="其他需要说明的信息"
        />
      </el-form-item>
      
      <!-- 确认信息 -->
      <el-divider content-position="left">确认信息</el-divider>
      <el-form-item label="考生确认签名">
        <el-upload
          :limit="1"
          :auto-upload="false"
          :on-change="handleSignatureUpload"
          accept=".jpg,.jpeg,.png"
          list-type="picture-card"
        >
          <el-icon><EditPen /></el-icon>
          <template #tip>
            <div class="el-upload__tip">上传考生签名照片</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="submitCheckOut" type="primary" :loading="formLoading">确认签退</el-button>
      <el-button @click="printCheckOutSlip" type="success">打印签退单</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { EditPen } from '@element-plus/icons-vue'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()

const selectedCandidate = ref(null)
const candidateList = ref([])

const checkOutForm = ref({
  candidateSearch: '',
  candidateId: '',
  checkOutTime: '',
  checkOutType: 'normal',
  examCompletion: 'completed',
  paperSubmission: [] as string[],
  itemsReturn: [] as string[],
  examAnomalies: [] as string[],
  anomalyDescription: '',
  immediateScore: false,
  theoryScore: undefined,
  practiceScore: undefined,
  overallEvaluation: 4,
  evaluatorComments: '',
  checkOutRemark: '',
  signature: null
})

const checkOutRules = ref({
  candidateSearch: [{ required: true, message: '请搜索并选择考生', trigger: 'blur' }],
  checkOutTime: [{ required: true, message: '请选择签退时间', trigger: 'change' }],
  checkOutType: [{ required: true, message: '请选择签退类型', trigger: 'change' }],
  examCompletion: [{ required: true, message: '请选择考试完成情况', trigger: 'change' }]
})

// 计算考试时长
const examDurationDisplay = computed(() => {
  if (!selectedCandidate.value || !checkOutForm.value.checkOutTime) {
    return '0'
  }
  
  const checkInTime = new Date(selectedCandidate.value.checkInTime)
  const checkOutTime = new Date(checkOutForm.value.checkOutTime)
  const durationMs = checkOutTime.getTime() - checkInTime.getTime()
  const durationMinutes = Math.floor(durationMs / (1000 * 60))
  
  return durationMinutes > 0 ? durationMinutes.toString() : '0'
})

// 监听签退时间变化，自动设置默认时间
watch(() => selectedCandidate.value, () => {
  if (selectedCandidate.value) {
    checkOutForm.value.checkOutTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
  }
})

const getExamStatusName = (status: string) => {
  const statusMap = {
    'checked_in': '已签到',
    'in_progress': '考试中',
    'completed': '已完成',
    'checked_out': '已签退'
  }
  return statusMap[status] || status
}

const getExamStatusColor = (status: string) => {
  const colorMap = {
    'checked_in': 'warning',
    'in_progress': 'primary',
    'completed': 'success',
    'checked_out': 'info'
  }
  return colorMap[status] || 'info'
}

const searchCandidate = () => {
  if (!checkOutForm.value.candidateSearch.trim()) {
    candidateList.value = []
    return
  }
  
  // TODO: 实际搜索已签到的考生
  candidateList.value = [
    {
      id: 1,
      candidateName: '张三',
      idCard: '123456789012345678',
      examNo: 'EX202312001',
      professionName: '电工',
      examSession: '第一场次',
      checkInTime: '2023-12-15 09:00:00',
      examStatus: 'in_progress'
    },
    {
      id: 2,
      candidateName: '李四',
      idCard: '123456789012345679',
      examNo: 'EX202312002',
      professionName: '焊工',
      examSession: '第一场次',
      checkInTime: '2023-12-15 09:05:00',
      examStatus: 'completed'
    }
  ].filter(candidate => 
    (candidate.candidateName.includes(checkOutForm.value.candidateSearch) ||
     candidate.idCard.includes(checkOutForm.value.candidateSearch) ||
     candidate.examNo.includes(checkOutForm.value.candidateSearch)) &&
    candidate.examStatus !== 'checked_out' // 排除已签退的考生
  )
}

const selectCandidate = (candidate: any) => {
  selectedCandidate.value = candidate
  checkOutForm.value.candidateId = candidate.id
  checkOutForm.value.candidateSearch = candidate.candidateName
  candidateList.value = []
  
  // 设置默认签退时间为当前时间
  checkOutForm.value.checkOutTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
}

const handleSignatureUpload = (file: any) => {
  checkOutForm.value.signature = file.raw
}

const submitCheckOut = async () => {
  if (!selectedCandidate.value) {
    ElMessage.warning('请先搜索并选择考生')
    return
  }
  
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  formLoading.value = true
  try {
    const checkOutData = {
      candidateId: selectedCandidate.value.id,
      candidateName: selectedCandidate.value.candidateName,
      examNo: selectedCandidate.value.examNo,
      examDuration: parseInt(examDurationDisplay.value),
      ...checkOutForm.value
    }
    
    // TODO: 提交签退数据
    console.log('考生签退:', checkOutData)
    
    dialogVisible.value = false
    emit('success')
    ElMessage.success(`${selectedCandidate.value.candidateName} 签退成功`)
  } finally {
    formLoading.value = false
  }
}

const printCheckOutSlip = () => {
  if (!selectedCandidate.value) {
    ElMessage.warning('请先完成签退')
    return
  }
  
  // TODO: 打印签退单
  ElMessage.info('签退单打印功能开发中...')
}

const resetForm = () => {
  checkOutForm.value = {
    candidateSearch: '',
    candidateId: '',
    checkOutTime: '',
    checkOutType: 'normal',
    examCompletion: 'completed',
    paperSubmission: [],
    itemsReturn: [],
    examAnomalies: [],
    anomalyDescription: '',
    immediateScore: false,
    theoryScore: undefined,
    practiceScore: undefined,
    overallEvaluation: 4,
    evaluatorComments: '',
    checkOutRemark: '',
    signature: null
  }
  
  selectedCandidate.value = null
  candidateList.value = []
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const open = () => {
  dialogVisible.value = true
  resetForm()
}

defineExpose({ open })
</script> 